package com.ekeyman.securecreditlib.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.ekeyman.securecredit.dto.CreditCardGrid;
import com.ekeyman.securecreditlib.domain.CreditCard;
import com.ekeymanlib.dto.SearchFilter;

@Repository("creditCardDao")
public class CreditCardDaoImpl extends AbstractDao implements CreditCardDao {

	public void saveCreditCard(CreditCard creditCard){
		getHibernateTemplate().saveOrUpdate(creditCard);
	}
	
	@SuppressWarnings("unchecked")
	public CreditCard findCreditCard(String fourDigits, String nameOnCard){
		
		CreditCard creditCard = null;
		
		String queryString ="from CreditCard as cc " +
		"where cc.fourDigits = :fourDigits " +
		"and cc.nameOnCard = :nameOnCard ";
		
		String[] paramNames = new String[2];
		paramNames[0] = "fourDigits";
		paramNames[1] = "nameOnCard";
		
		Object[] values = new Object[2];
		values[0] = fourDigits;
		values[1] = nameOnCard;
		
		List<CreditCard> creditCards = getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
		
		if(creditCards != null && !creditCards.isEmpty()){
			creditCard = creditCards.get(0);
		}		
		
		return creditCard;
	}
	
	public CreditCard findCreditCard(long id){
		return (CreditCard)getHibernateTemplate().get(CreditCard.class, id);
	}
	
	public void deleteCreditCard(long id){
		
		CreditCard creditCard = (CreditCard)getHibernateTemplate().get(CreditCard.class, id);
		
		if(creditCard != null){
			getHibernateTemplate().delete(creditCard);
		}
	}	
	
	public void updateCreditCard(CreditCardGrid creditCardGrid){

		CreditCard creditCard = (CreditCard)getHibernateTemplate().get(CreditCard.class, creditCardGrid.getId());
		
		if(creditCard != null){
			creditCard.setCreditCardNumber(creditCardGrid.getCreditCardNumber());
			creditCard.setNameOnCard(creditCardGrid.getNameOnCard());
			creditCard.setCardType(creditCardGrid.getCardType());
			creditCard.setFourDigits(creditCardGrid.getFourDigits());
			creditCard.setExpirationDate(creditCardGrid.getExpirationDate());
			getHibernateTemplate().update(creditCard);
		}
	}	
	
	@SuppressWarnings("unchecked")
	public List<CreditCard> listCreditCards(List<SearchFilter> searchFilters, 
			String sortIndex, String sortOrder, int firstResult, int maxResults) {

		return findAll(searchFilters, CreditCard.class, 
				sortIndex, sortOrder, firstResult, maxResults);
	}
	
	public long getCreditCardCount(List<SearchFilter> searchFilters) {

		return getCount(searchFilters, CreditCard.class);
	}
}
